"""
协议管理器模块
用于动态加载和管理不同的升级协议
"""

from PySide6.QtWidgets import QWidget, QVBoxLayout
from PySide6.QtCore import QObject, Signal
import importlib
import os


class ProtocolManager(QObject):
    """协议管理器类"""
    
    # 信号定义
    status_update = Signal(str, str)  # 状态更新信号 (消息, 颜色)
    progress_update = Signal(int, int)  # 进度更新信号
    
    def __init__(self):
        super().__init__()
        self.current_protocol = None
        self.current_config_widget = None
        self.protocol_modules = {}
        self.load_available_protocols()
        
    def load_available_protocols(self):
        """加载可用的协议模块"""
        # Ymodem协议
        try:
            from ymodem_protocol import YmodemProtocol, YmodemConfigWidget
            self.protocol_modules['Ymodem'] = {
                'protocol_class': YmodemProtocol,
                'config_widget_class': YmodemConfigWidget,
                'name': 'Ymodem',
                'description': 'Ymodem文件传输协议'
            }
        except ImportError:
            pass
            
        # 可以在这里添加其他协议
        # self.protocol_modules['Xmodem'] = {...}
        # self.protocol_modules['自定义协议'] = {...}
        
    def get_available_protocols(self):
        """获取可用协议列表"""
        return list(self.protocol_modules.keys())
        
    def create_protocol_instance(self, protocol_name, config):
        """创建协议实例"""
        if protocol_name not in self.protocol_modules:
            raise ValueError(f"不支持的协议: {protocol_name}")
            
        protocol_info = self.protocol_modules[protocol_name]
        protocol_class = protocol_info['protocol_class']
        
        # 创建协议实例
        protocol_instance = protocol_class(config)
        
        # 连接信号
        if hasattr(protocol_instance, 'status_update'):
            protocol_instance.status_update.connect(
                lambda msg: self.status_update.emit(msg, "blue")
            )
            
        if hasattr(protocol_instance, 'progress_update'):
            protocol_instance.progress_update.connect(self.progress_update.emit)
            
        return protocol_instance
        
    def create_config_widget(self, protocol_name):
        """创建协议配置界面"""
        if protocol_name not in self.protocol_modules:
            return None
            
        protocol_info = self.protocol_modules[protocol_name]
        config_widget_class = protocol_info['config_widget_class']
        
        return config_widget_class()
        
    def get_protocol_description(self, protocol_name):
        """获取协议描述"""
        if protocol_name in self.protocol_modules:
            return self.protocol_modules[protocol_name]['description']
        return "未知协议"
        
    def validate_protocol_config(self, protocol_name, config):
        """验证协议配置"""
        if protocol_name not in self.protocol_modules:
            return False, "不支持的协议"
            
        # 基础验证
        if not config:
            return False, "配置为空"
            
        # 协议特定验证
        if protocol_name == 'Ymodem':
            return self._validate_ymodem_config(config)
            
        return True, "配置有效"
        
    def _validate_ymodem_config(self, config):
        """验证Ymodem协议配置"""
        try:
            packet_size = int(config.get('packet_size', 128))
            if packet_size not in [128, 1024]:
                return False, "数据包大小必须为128或1024字节"
                
            timeout = int(config.get('timeout', 1000))
            if timeout < 100 or timeout > 10000:
                return False, "超时时间必须在100-10000ms之间"
                
            max_retries = int(config.get('max_retries', 3))
            if max_retries < 1 or max_retries > 10:
                return False, "重试次数必须在1-10次之间"
                
            return True, "Ymodem配置有效"
            
        except ValueError as e:
            return False, f"配置参数格式错误: {str(e)}"


class DynamicProtocolWidget(QWidget):
    """动态协议配置界面容器"""
    
    def __init__(self):
        super().__init__()
        self.layout = QVBoxLayout(self)
        self.current_widget = None
        
    def set_protocol_widget(self, widget):
        """设置当前协议配置界面"""
        # 清除当前界面
        if self.current_widget:
            self.layout.removeWidget(self.current_widget)
            self.current_widget.setParent(None)
            
        # 设置新界面
        self.current_widget = widget
        if widget:
            self.layout.addWidget(widget)
            
    def get_current_widget(self):
        """获取当前配置界面"""
        return self.current_widget
        
    def clear(self):
        """清空界面"""
        self.set_protocol_widget(None) 